/* -*- C++ -*- */

//=============================================================================
/*
 * @author Feloweria <380374483@qq.com>
 * Copyright (C) Feloweria
 * 
 * $ID 2013-06-15 07:22:08 PM
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @version 1.0
 */
//=============================================================================

#ifndef FELOWRIA_CPU_AFFINITY_INCLUDE
#define FELOWRIA_CPU_AFFINITY_INCLUDE

#include <sched.h>

#include "Felowria.h"
#include "Platform/SysInfo.h"

FELOWRIA_BEGIN
/*
 * @class CPU_Affinity
 * @brief the CPU_Affinity data struction represents a set of CPUs,
 * CPU_Affinity are used by  Affinity and similiar interfaces.
 */
class CPU_Affinity
{
public:
	typedef	int32	CPU_TYPE;
	typedef	uint32	CPU_SIZE;
	typedef uint32	CPU_COUNT;
	
public:
	const static CPU_TYPE	NONE_CPU = -1;
	
public:
	explicit CPU_Affinity(CPU_TYPE cpu = NONE_CPU);
	CPU_Affinity(const CPU_Affinity& affinity);
	~CPU_Affinity();
	
public:
	bool AddCPU(CPU_TYPE cpu);
	bool RemoveCPU(CPU_TYPE cpu);
	bool Clear();
	
	CPU_SIZE	 Size() const {return size;}
	CPU_COUNT	 Count() const {return count;}
	
	bool IsScope(CPU_TYPE cpu) const
	{
		return cpu > NONE_CPU && cpu < info.core_num;
	}
	
	bool IsExist(CPU_TYPE cpu) const
	{
		if(!IsScope(cpu))
			return false;
		
		return CPU_ISSET_S(cpu,size,cpu_set);
	}
	
public:
	operator cpu_set_t*() {return cpu_set;}
	operator const cpu_set_t*() const {return cpu_set;}
	
	bool operator==(const CPU_Affinity& affinity);
	CPU_Affinity& operator=(const CPU_Affinity& affinity);

	CPU_Affinity operator&(const CPU_Affinity &affinity) const;
	CPU_Affinity& operator&=(const CPU_Affinity &affinity);
	
	CPU_Affinity operator|(const CPU_Affinity &affinity) const;
	CPU_Affinity& operator|=(const CPU_Affinity &affinity);
	
private:
	cpu_set_t *cpu_set;
	CPU_SIZE size;
	CPU_COUNT count;
	
};// class CPU_Affinity

FELOWRIA_END

#ifdef __linux__
#include "CPU_Affinity.inl"
#endif // __linux__
#endif // FELOWRIA_CPU_AFFINITY_INCLUDE
